package com.example.demo.config;

import com.alibaba.fastjson.JSON;
import com.example.demo.controller.data.ReturnData;
import com.example.demo.entity.Admin;
import com.example.demo.entity.User;
import com.example.demo.util.TokenUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义一个拦截器类
 */

public class MyInterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 在这里会被拦截，否则放行
        if (handler instanceof HandlerMethod) {//是不是属于拦截的路径
            System.out.println(request.getRequestURL() + "这个方法被拦截");
            //设置请求内容的编码，防止乱码
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有域名跨域访问
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // 允许的请求方法
            response.setHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的请求头
            //从 http 请求头中取出 token
            String token = request.getHeader("token");
            if (token == null || token.equals("")) {//不存在token,则告诉前端需要登录
                getJson(ReturnData.error("请先登录"), response);
                return false;
            } else {//如果存在 ，则表示已经登陆
//                ReturnData returnData = TokenUtil.checkToken(token);

                token = TokenUtil.decoder(token);//进行解密
                if (!token.contains("|")) {//判断token有没有|这个符号
                    getJson(ReturnData.error("token错误"), response);
                    return false;
                }
                String[] strs = token.split("\\|");//加两个斜杠才能识别是|，把token分割成两部分
                long time = Long.parseLong(strs[1]);//过期时间 Long.parseLong把字符串转化为数字
                long now = System.currentTimeMillis();//当前时间
                if (time < now) {
                    getJson(ReturnData.error("token过期，请重新登录"), response);
                    return false;
                }
                try {
                    User user = (User) redisTemplate.opsForValue().get("wx" + strs[0]);//根据用户名查找redis缓存，拿到对应用户信息
                    if (user == null) {
                        getJson(ReturnData.error("token过期，请重新登录"), response);
                        return false;
                    }
                }catch (ClassCastException e){
                    Admin user = (Admin) redisTemplate.opsForValue().get("wx" + strs[0]);//根据用户名查找redis缓存，拿到对应用户信息
                    if (user == null) {
                        getJson(ReturnData.error("token过期，请重新登录"), response);
                        return false;
                    }
                }
                return true;
            }
        }
        return true;
    }

    public void getJson(Object object, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(JSON.toJSONString(object));
    }
}
